<template>
  <div>
    <Row
      style="align-items: flex-start;margin-bottom:5px;display:block;padding-bottom: 20px;"
    >
      <Col :lg="10" :xs="22" offset="1">
        <Button style="margin-left: 5px;" type="primary">导入</Button>
        <Button style="margin-left: 5px;" type="success" @click="addRow1"
          >新增</Button
        >
        <Button style="margin-left: 5px;" type="error" @click="delRow1"
          >删除</Button
        >
        <Button style="margin-left: 5px;" type="info" @click="saveData1"
          >保存</Button
        >
        <Button style="margin-left: 5px;" @click="exportExcel2">导出</Button>
        <vxe-table
          ref="xTable1"
          height="400"
          border
          highlight-hover-row
          show-overflow
          :edit-rules="validRules"
          :data="tablePage.listPage"
          :print-config="{}"
          :export-config="{}"
          :loading="loading"
          :edit-config="{ trigger: 'click', mode: 'cell' }"
        >
          <vxe-column type="checkbox" width="60"></vxe-column>
          <vxe-column type="seq" width="60"></vxe-column>
          <vxe-column
            field="pedal"
            title="油门"
            :edit-render="{ name: 'input' }"
          ></vxe-column>
          <vxe-column
            field="gear12UpshifttingSpeed"
            title="1->2"
            :edit-render="{ name: 'input' }"
          ></vxe-column>
          <vxe-column
            field="gear23UpshifttingSpeed"
            title="2->3"
            :edit-render="{ name: 'input' }"
          ></vxe-column>
          <vxe-column
            field="gear34UpshifttingSpeed"
            title="3->4"
            :edit-render="{ name: 'input' }"
          ></vxe-column>
          <vxe-column
            field="gear45UpshifttingSpeed"
            title="4->5"
            :edit-render="{ name: 'input' }"
          ></vxe-column>
          <vxe-column
            field="gear56UpshifttingSpeed"
            title="5->6"
            :edit-render="{ name: 'input' }"
          ></vxe-column>
        </vxe-table>
        <div style="margin-top: 20px;"></div>
        <Button style="margin-left: 5px;" type="primary">导入</Button>
        <Button style="margin-left: 5px;" type="success" @click="addRow2"
          >新增</Button
        >
        <Button style="margin-left: 5px;" type="error" @click="delRow2"
          >删除</Button
        >
        <Button style="margin-left: 5px;" type="info" @click="saveData1"
          >保存</Button
        >
        <Button style="margin-left: 5px;" @click="exportExcel3">导出</Button>
        <vxe-table
          ref="xTable2"
          height="400"
          border
          highlight-hover-row
          show-overflow
          :data="tableData2"
          :edit-config="{ trigger: 'click', mode: 'cell' }"
        >
          <vxe-column type="checkbox" width="60"></vxe-column>
          <vxe-column type="seq" width="60"></vxe-column>
          <vxe-column
            field="pedal"
            title="油门"
            :edit-render="{ name: 'input' }"
          ></vxe-column>
          <vxe-column
            field="gear21UpshifttingSpeed"
            title="2->1"
            :edit-render="{ name: 'input' }"
          ></vxe-column>
          <vxe-column
            field="gear32UpshifttingSpeed"
            title="3->2"
            :edit-render="{ name: 'input' }"
          ></vxe-column>
          <vxe-column
            field="gear43UpshifttingSpeed"
            title="4->3"
            :edit-render="{ name: 'input' }"
          ></vxe-column>
          <vxe-column
            field="gear54UpshifttingSpeed"
            title="5->4"
            :edit-render="{ name: 'input' }"
          ></vxe-column>
          <vxe-column
            field="gear65UpshifttingSpeed"
            title="6->5"
            :edit-render="{ name: 'input' }"
          ></vxe-column>
        </vxe-table>
      </Col>
      <Col :lg="12" :xs="22" offset="1">
        <div style="height:400px;" id="c"></div>
      </Col>
    </Row>
  </div>
</template>

<script>
import { gearboxEfficiencyApi } from "@/api/gearbox-efficiency";
import { gearboxShiftApi } from "@/api/gearbox-shift";
import XLSX, { WorkSheet } from "xlsx";

export default {
  name: "ChangeMap",
  props: {
    gearboxId: {
      type: Number
    }
  },
  data() {
    return {
      tableData: [], // 表格列表数据
      tablePage: {
        currentPage: 1,
        pageSize: 10,
        totalResult: 0,
        listPage: []
      },
      loading: false,
      validRules: {
        inputSpeed: [
          { pattern: "^[0-9]+.?[0-9]*$", message: "请输入数字类型" }
        ],
        unloadLoss: [
          { pattern: "^[0-9]+.?[0-9]*$", message: "请输入数字类型" }
        ],
        loadLossCoefficient: [
          { pattern: "^[0-9]+.?[0-9]*$", message: "请输入数字类型" }
        ],
        gear: [{ pattern: "^[0-9]+.?[0-9]*$", message: "请输入数字类型" }]
      }
    };
  },
  watch: {},
  filters: {},
  created() {
    this.gearboxId = this.$route.query.id;
  },
  mounted() {
    // 初始化数据
    this.initData();
    this.initData1();
  },
  methods: {
    // 翻页
    handlePageChange({ currentPage, pageSize }) {
      this.tablePage.currentPage = currentPage;
      this.tablePage.pageSize = pageSize;
      this.findList();
    },

    findList() {
      // 总数据
      this.tablePage.totalResult = this.tableData.length;
      this.tablePage.listPage = this.tableData.slice(
        (this.tablePage.currentPage - 1) * this.tablePage.pageSize,
        this.tablePage.currentPage * this.tablePage.pageSize
      );
    },

    exportExcel1() {
      const workBook = XLSX.utils.table_to_book(
        this.$refs.xTable.$el.querySelector(".body--wrapper>.vxe-table--body")
      );
      XLSX.writeFile(workBook, "效率MAP.xlsx");
    },
    exportExcel2() {
      const workBook = XLSX.utils.table_to_book(
        this.$refs.xTable1.$el.querySelector(".body--wrapper>.vxe-table--body")
      );
      XLSX.writeFile(workBook, "换挡MAP1.xlsx");
    },
    exportExcel3() {
      const workBook = XLSX.utils.table_to_book(
        this.$refs.xTable2.$el.querySelector(".body--wrapper>.vxe-table--body")
      );
      XLSX.writeFile(workBook, "换挡MAP2.xlsx");
    },

    /**
     * @desc 添加行数据
     */
    addRow() {
      const $table = this.$refs.xTable;
      const record = {
        gear: null,
        inputSpeed: null,
        unloadLoss: null,
        loadLossCoefficient: null,
        index: this.tableData.length
      };
      this.tableData.push(record);
      const { row: newRow } = $table.insertAt(record, -1);
      $table.setActiveCell(newRow, "gear");
    },

    /**
     * @desc 删除行数据
     */
    async delRow() {
      const { rows } = await this.$refs.xTable.removeCheckboxRow();
      if (rows && rows.length > 0) {
        const newArr = [];
        const tempar = rows.map(item => item.index);
        this.tableData.forEach(item => {
          if (tempar.indexOf(item.index) == -1) {
            newArr.push(item);
          }
        });
        this.tableData = newArr;
      } else {
        this.$Message.warning("没有可删除的数据！");
      }
    },

    saveData() {
      // 数据验证
      if (!(this.tableData && this.tableData.length > 0)) {
        this.$Message.warning("没有可保存的数据！");
        return;
      }
      // 挡位
      const gear = this.tableData.map(item => item.gear);
      // 输入转速(rpm)
      const inputSpeed = this.tableData.map(item => item.inputSpeed);
      // 空载损失(kW)
      const unloadLoss = this.tableData.map(item => item.unloadLoss);
      // 负载损失系数(%)
      const loadLossCoefficient = this.tableData.map(
        item => item.loadLossCoefficient
      );

      // 变速箱_id
      const gearboxId = this.gearboxId;

      const param = {
        gear: JSON.stringify(gear),
        inputSpeed: JSON.stringify(inputSpeed),
        unloadLoss: JSON.stringify(unloadLoss),
        loadLossCoefficient: JSON.stringify(loadLossCoefficient),
        tableData: JSON.stringify(this.tableData),
        gearboxId: gearboxId
      };
      gearboxEfficiencyApi.addGearboxEfficiency(param).then(res => {
        this.$Message.warning("保存成功");
      });
    },

    /**
     * 初始化列表数据
     */
    initData() {
      gearboxEfficiencyApi.getByGearboxId(this.gearboxId).then(res => {
        console.log("---->>>", res);
        const data = res.data;
        if (data) {
          // 组合table数据
          const tableData = JSON.parse(data.tableData);
          if (tableData && tableData.length > 0) {
            this.tableData = tableData;
          } else {
            return;
          }
          this.renderEchart();
        }
      });
    },

    /// /////////////////////////////////////////第一个曲线 end

    /**
     * @desc 添加行数据
     */
    addRow1() {
      const $table = this.$refs.xTable1;
      const record = {
        index: this.tableData1.length,
        pedal: null,
        gear12UpshifttingSpeed: null,
        gear23UpshifttingSpeed: null,
        gear34UpshifttingSpeed: null,
        gear45UpshifttingSpeed: null,
        gear56UpshifttingSpeed: null
      };
      this.tableData1.push(record);
      const { row: newRow } = $table.insertAt(record, -1);
      $table.setActiveCell(newRow, "pedal");
    },
    addRow2() {
      const $table = this.$refs.xTable2;
      const record = {
        index: this.tableData1.length,
        pedal: null,
        gear21UpshifttingSpeed: null,
        gear32UpshifttingSpeed: null,
        gear43UpshifttingSpeed: null,
        gear54UpshifttingSpeed: null,
        gear65UpshifttingSpeed: null
      };
      this.tableData2.push(record);
      const { row: newRow } = $table.insertAt(record, -1);
      $table.setActiveCell(newRow, "pedal");
    },
    /**
     * @desc 删除行数据
     */
    async delRow1() {
      const { rows } = await this.$refs.xTable1.removeCheckboxRow();
      if (rows && rows.length > 0) {
        const newArr = [];
        const tempar = rows.map(item => item.index);
        this.tableData1.forEach(item => {
          if (tempar.indexOf(item.index) == -1) {
            newArr.push(item);
          }
        });
        this.tableData1 = newArr;
      } else {
        this.$Message.warning("没有可删除的数据！");
      }
    },
    async delRow2() {
      const { rows } = await this.$refs.xTable2.removeCheckboxRow();
      if (rows && rows.length > 0) {
        const newArr = [];
        const tempar = rows.map(item => item.index);
        this.tableData2.forEach(item => {
          if (tempar.indexOf(item.index) == -1) {
            newArr.push(item);
          }
        });
        this.tableData2 = newArr;
      } else {
        this.$Message.warning("没有可删除的数据！");
      }
    },

    renderEchart1() {
      // 获取油门开度  y轴数据
      let yAxisData = null;

      const pedals1 = this.tableData1.map(item => item.pedal);
      const pedals2 = this.tableData2.map(item => item.pedal);
      if ((pedals2 && pedals2.length > 0) || (pedals1 && pedals1.length > 0)) {
        if (pedals2 && pedals2.length > 0) {
          if (pedals1 && pedals1.length > 0) {
            pedals2.forEach(item => {
              if (pedals1.indexOf(item) == -1) {
                pedals1.push(item);
              }
            });
            yAxisData = pedals1;
          } else {
            yAxisData = pedals2;
          }
        } else {
          yAxisData = pedals1;
        }
      } else {
        return;
      }

      // x轴数据
      const series = [];
      if (this.tableData1 && this.tableData1.length > 0) {
        const gear12UpshifttingSpeeds = this.tableData1.map(
          item => item.gear12UpshifttingSpeed
        );
        const gear23UpshifttingSpeeds = this.tableData1.map(
          item => item.gear23UpshifttingSpeed
        );
        const gear34UpshifttingSpeeds = this.tableData1.map(
          item => item.gear34UpshifttingSpeed
        );
        const gear45UpshifttingSpeeds = this.tableData1.map(
          item => item.gear45UpshifttingSpeed
        );
        const gear56UpshifttingSpeeds = this.tableData1.map(
          item => item.gear56UpshifttingSpeed
        );
        if (gear12UpshifttingSpeeds && gear12UpshifttingSpeeds.length > 0) {
          series.push({
            name: "1-2",
            type: "line",
            symbolSize: 6,
            symbol: "circle",
            smooth: true,
            lineStyle: {
              width: 2,
              shadowColor: "rgba(0,0,0,0.3)",
              shadowBlur: 10,
              shadowOffsetY: 2,
              type: "dashed"
            },
            data: gear12UpshifttingSpeeds
          });
        }
        if (gear23UpshifttingSpeeds && gear23UpshifttingSpeeds.length > 0) {
          series.push({
            name: "2-3",
            type: "line",
            symbolSize: 6,
            symbol: "circle",
            smooth: true,
            lineStyle: {
              width: 2,
              shadowColor: "rgba(0,0,0,0.3)",
              shadowBlur: 10,
              shadowOffsetY: 2,
              type: "dashed"
            },
            data: gear23UpshifttingSpeeds
          });
        }
        if (gear34UpshifttingSpeeds && gear34UpshifttingSpeeds.length > 0) {
          series.push({
            name: "3-4",
            type: "line",
            symbolSize: 6,
            symbol: "circle",
            smooth: true,
            lineStyle: {
              width: 2,
              shadowColor: "rgba(0,0,0,0.3)",
              shadowBlur: 10,
              shadowOffsetY: 2,
              type: "dashed"
            },
            data: gear34UpshifttingSpeeds
          });
        }
        if (gear45UpshifttingSpeeds && gear45UpshifttingSpeeds.length > 0) {
          series.push({
            name: "4-5",
            type: "line",
            symbolSize: 6,
            symbol: "circle",
            smooth: true,
            lineStyle: {
              width: 2,
              shadowColor: "rgba(0,0,0,0.3)",
              shadowBlur: 10,
              shadowOffsetY: 2,
              type: "dashed"
            },
            data: gear45UpshifttingSpeeds
          });
        }
        if (gear56UpshifttingSpeeds && gear56UpshifttingSpeeds.length > 0) {
          series.push({
            name: "5-6",
            type: "line",
            symbolSize: 6,
            symbol: "circle",
            smooth: true,
            lineStyle: {
              width: 2,
              shadowColor: "rgba(0,0,0,0.3)",
              shadowBlur: 10,
              shadowOffsetY: 2,
              type: "dashed"
            },
            data: gear56UpshifttingSpeeds
          });
        }
      }
      if (this.tableData2 && this.tableData2.length > 0) {
        const gear21UpshifttingSpeeds = this.tableData2.map(
          item => item.gear21UpshifttingSpeed
        );
        const gear32UpshifttingSpeeds = this.tableData2.map(
          item => item.gear32UpshifttingSpeed
        );
        const gear43UpshifttingSpeeds = this.tableData2.map(
          item => item.gear43UpshifttingSpeed
        );
        const gear54UpshifttingSpeeds = this.tableData2.map(
          item => item.gear54UpshifttingSpeed
        );
        const gear65UpshifttingSpeeds = this.tableData2.map(
          item => item.gear65UpshifttingSpeed
        );
        if (gear21UpshifttingSpeeds && gear21UpshifttingSpeeds.length > 0) {
          series.push({
            name: "2-1",
            type: "line",
            symbolSize: 6,
            symbol: "circle",
            smooth: true,
            lineStyle: {
              width: 2,
              shadowColor: "rgba(0,0,0,0.3)",
              shadowBlur: 10,
              shadowOffsetY: 2
            },
            data: gear21UpshifttingSpeeds
          });
        }
        if (gear32UpshifttingSpeeds && gear32UpshifttingSpeeds.length > 0) {
          series.push({
            name: "3-2",
            type: "line",
            symbolSize: 6,
            symbol: "circle",
            smooth: true,
            lineStyle: {
              width: 2,
              shadowColor: "rgba(0,0,0,0.3)",
              shadowBlur: 10,
              shadowOffsetY: 2
            },
            data: gear32UpshifttingSpeeds
          });
        }
        if (gear43UpshifttingSpeeds && gear43UpshifttingSpeeds.length > 0) {
          series.push({
            name: "4-3",
            type: "line",
            symbolSize: 6,
            symbol: "circle",
            smooth: true,
            lineStyle: {
              width: 2,
              shadowColor: "rgba(0,0,0,0.3)",
              shadowBlur: 10,
              shadowOffsetY: 2
            },
            data: gear43UpshifttingSpeeds
          });
        }
        if (gear54UpshifttingSpeeds && gear54UpshifttingSpeeds.length > 0) {
          series.push({
            name: "5-4",
            type: "line",
            symbolSize: 6,
            symbol: "circle",
            smooth: true,
            lineStyle: {
              width: 2,
              shadowColor: "rgba(0,0,0,0.3)",
              shadowBlur: 10,
              shadowOffsetY: 2
            },
            data: gear54UpshifttingSpeeds
          });
        }
        if (gear65UpshifttingSpeeds && gear65UpshifttingSpeeds.length > 0) {
          series.push({
            name: "6-5",
            type: "line",
            symbolSize: 6,
            symbol: "circle",
            smooth: true,
            lineStyle: {
              width: 2,
              shadowColor: "rgba(0,0,0,0.3)",
              shadowBlur: 10,
              shadowOffsetY: 2
            },
            data: gear65UpshifttingSpeeds
          });
        }
      }

      const option = {
        legend: {
          data: ["1-2", "2-3", "3-4", "4-5", "5-6"]
        },
        tooltip: {
          trigger: "axis",
          formatter: "speed : <br/>{b}km"
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true
        },
        xAxis: {
          type: "value",
          name: "车速(km/h)"
        },
        yAxis: {
          name: "油门开度",
          type: "category",
          axisLine: { onZero: false },
          /* axisLabel: {
            formatter: '{value} %'
          }, */
          boundaryGap: false,
          data: yAxisData
        },
        series: series
      };

      let myChart = this.echarts.init(document.getElementById("b"));
      myChart.setOption(option);
    },

    saveData1() {
      // 数据验证
      if (
        !(this.tableData1 && this.tableData1.length > 0) &&
        !(this.tableData2 && this.tableData2.length > 0)
      ) {
        this.$Message.warning("没有可保存的数据！");
        return;
      }

      // 变速箱_id
      const gearboxId = this.gearboxId;

      const param = {
        tableData1: JSON.stringify(this.tableData1),
        tableData2: JSON.stringify(this.tableData2),
        gearboxId: gearboxId
      };
      gearboxShiftApi.addGearboxShift(param).then(res => {
        this.$Message.warning("保存成功");
      });
    },
    initData1() {
      gearboxShiftApi.getByGearboxId(this.gearboxId).then(res => {
        const data = res.data;
        if (data) {
          // 组合table数据
          const tableData1 = JSON.parse(data.tableData1);
          if (tableData1 && tableData1.length > 0) {
            this.tableData1 = tableData1;
          }
          const tableData2 = JSON.parse(data.tableData2);
          if (tableData2 && tableData2.length > 0) {
            this.tableData2 = tableData2;
          }
          this.renderEchart();
        }
      });
    }
  }
};
</script>
